package com.gnerv.rabbitmq.agent.command;

import com.gnerv.rabbitmq.agent.model.entity.Node;
import com.gnerv.rabbitmq.agent.tools.ExecTools;
import lombok.Data;

import java.io.File;
import java.util.List;
import java.util.Map;

import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_MAX_LENGTH;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_MAX_LENGTH_BYTES;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_MAX_LENGTH_BYTES_FORMAT;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_MAX_LENGTH_FORMAT;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_MESSAGE_TTL;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_MESSAGE_TTL_FORMAT;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_QUEUE_TYPE;
import static com.gnerv.rabbitmq.agent.constants.QueueArgument.X_QUEUE_TYPE_FORMAT;


/**
 * @author Gnerv LiGen
 */
@Data
public abstract class AbstractRabbitmqCommand {

    private Node node;
    private List<String> commands;

    public abstract ExecTools.ExecResult run(List<String> commands);

    final ExecTools.ExecResult run(String command) {
        return ExecTools.run(command, new File(node.getPath()));
    }

    final ExecTools.ExecResult run(String command, File file) {
        return ExecTools.run(command, file);
    }

    public String convertArguments(Map<String, Object> arguments) {
        StringBuilder stringBuilder = new StringBuilder();
        int size = 1;
        for (String key : arguments.keySet()) {
            switch (key) {
                case X_MAX_LENGTH:
                    // {"x-max-length",100000}
                    stringBuilder.append(String.format(X_MAX_LENGTH_FORMAT, arguments.get(key)));
                    break;
                case X_MAX_LENGTH_BYTES:
                    // {"x-max-length-bytes",100000}
                    stringBuilder.append(String.format(X_MAX_LENGTH_BYTES_FORMAT, arguments.get(key)));
                    break;
                case X_QUEUE_TYPE:
                    // {"x-queue-type","classic"}
                    stringBuilder.append(String.format(X_QUEUE_TYPE_FORMAT, arguments.get(key)));
                    break;
                case X_MESSAGE_TTL:
                    // {"x-message-ttl",12312}
                    stringBuilder.append(String.format(X_MESSAGE_TTL_FORMAT, arguments.get(key)));
                    break;
                default:
                    break;
            }
            if (size < arguments.keySet().size()) {
                stringBuilder.append(",");
            }
            size++;
        }
        return stringBuilder.toString();
    }

}